{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dropout\n",
    ":label:`sec_dropout`\n",
    "\n",
    "在 :numref:`sec_weight_decay` 中，我们介绍了通过惩罚权重的$L_2$范数来正则化统计模型的经典方法。在概率角度看，我们可以通过以下论证来证明这一技术的合理性：我们已经假设了一个先验，即权重的值取自均值为0的高斯分布。更直观的是，我们可能会说，我们鼓励模型将其权重分散到许多特征中，而不是过于依赖少数潜在的虚假关联。\n",
    "\n",
    "## 重新审视过拟合\n",
    "\n",
    "当面对更多的特征而样本不足时，线性模型往往会过度拟合。当给出更多样本而不是特征，我们通常可以指望线性模型不会过拟合。不幸的是，线性模型泛化的可靠性是有代价的。简单地说，线性模型没有考虑到特征之间的交互作用。对于每个特征，线性模型必须指定正的或负的权重，而忽略上下文。\n",
    "\n",
    "在传统说法中，泛化性和灵活性之间的这种基本权衡被描述为*偏差-方差权衡*（bias-variance tradeoff）。线性模型有很高的偏差：它们只能表示一小类函数。然而，这些模型的方差很低：它们在不同的随机数据样本上给出了相似的结果。\n",
    "\n",
    "深度神经网络位于偏差-方差谱的另一端。与线性模型不同，神经网络并不局限于单独查看每个特征。它们可以学习特征之间的交互。例如，它们可能推断“尼日利亚”和“西联汇款”一起出现在电子邮件中表示垃圾邮件，但单独出现则不表示垃圾邮件。\n",
    "\n",
    "即使我们有比特征多得多的样本，深度神经网络也有可能过拟合。2017年，一组研究人员通过在随机标记的图像上训练深度网络。这展示了神经网络的极大灵活性。因为没有任何真实的模式将输入和输出联系起来，但他们发现，通过随机梯度下降优化的神经网络可以完美地标记训练集中的每一幅图像。想一想这意味着什么。如果标签是随机均匀分配的，并且有10个类别，那么在保留数据上没有分类器会取得高于10%的准确率。这里的泛化差距高达90%。如果我们的模型具有这么强的表达能力，以至于它们可以如此严重地过拟合，那么我们指望在什么时候它们不会过拟合呢？\n",
    "\n",
    "深度网络有着令人费解的泛化性质，而这种泛化性质的数学基础仍然是悬而未决的研究问题，我们鼓励面向理论的读者更深入地研究这个主题。目前，我们转向对实际工具的探究，这些工具倾向于经验上改进深层网络的泛化性。\n",
    "\n",
    "## 扰动的鲁棒性\n",
    "\n",
    "让我们简单地思考一下我们对一个好的预测模型的期待。我们期待它能在看不见的数据上有很好的表现。经典泛化理论认为，为了缩小训练和测试性能之间的差距，我们应该以简单的模型为目标。简单性以较小维度的形式出现。我们在 :numref:`sec_model_selection` 讨论线性模型的单项式函数时探讨了这一点。此外，正如我们在 :numref:`sec_weight_decay` 中讨论权重衰减（$L_2$正则化）时看到的那样，参数的范数也代表了一种有用的简单性度量。简单性的另一个有用角度是平滑性，即函数不应该对其输入的微小变化敏感。例如，当我们对图像进行分类时，我们预计向像素添加一些随机噪声应该是基本无影响的。\n",
    "\n",
    "1995年，克里斯托弗·毕晓普证明了具有输入噪声的训练等价于Tikhonov正则化 :cite:`Bishop.1995` ，从而将这一观点正式化。这项工作在要求函数光滑(因而简单)和要求它对输入中的扰动具有适应性之间有了明确的数学联系。\n",
    "\n",
    "然后，在2014年，斯里瓦斯塔瓦等人 :cite:`Srivastava.Hinton.Krizhevsky.ea.2014` 还就如何将毕晓普的想法应用于网络的内部层提出了一个聪明的想法。在训练过程中，他们建议在计算后续层之前向网络的每一层注入噪声。他们意识到，当训练一个有多层的深层网络时，注入噪声只会在输入-输出映射上增强平滑性。\n",
    "\n",
    "他们的想法被称为*丢弃法*（dropout），dropout在正向传播过程中，计算每一内部层的同时注入噪声，这已经成为训练神经网络的标准技术。这种方法之所以被称为 *dropout* ，因为我们从表面上看是在训练过程中丢弃（drop out）一些神经元。\n",
    "在整个训练过程的每一次迭代中，dropout包括在计算下一层之前将当前层中的一些节点置零。\n",
    "\n",
    "需要说明的是，我们将自己的叙述与毕晓普联系起来。关于dropout的原始论文出人意料地通过一个有性繁殖类比提供了直觉。作者认为，神经网络过拟合的特征是每一层都依赖于前一层激活值的特定模式，称这种情况为“共适应性”。他们声称，dropout会破坏共适应性，就像有性生殖会破坏共适应的基因一样。\n",
    "\n",
    "那么关键的挑战就是如何注入这种噪声。一种想法是以一种*无偏*的方式注入噪声。这样在固定住其他层时，每一层的期望值等于没有噪音时的值。\n",
    "\n",
    "在毕晓普的工作中，他将高斯噪声添加到线性模型的输入中。在每次训练迭代中，他将从均值为零的分布$\\epsilon \\sim \\mathcal{N}(0,\\sigma^2)$采样噪声添加到输入$\\mathbf{x}$，从而产生扰动点$\\mathbf{x}' = \\mathbf{x} + \\epsilon$。预期是$E[\\mathbf{x}'] = \\mathbf{x}$。\n",
    "\n",
    "在标准dropout正则化中，通过按保留（未丢弃）的节点的分数进行归一化来消除每一层的偏差。换言之，每个中间激活值$h$以*丢弃概率*$p$由随机变量$h'$替换，如下所示：\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "h' =\n",
    "\\begin{cases}\n",
    "    0 & \\text{ 概率为 } p \\\\\n",
    "    \\frac{h}{1-p} & \\text{ 其他情况}\n",
    "\\end{cases}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "根据设计，期望值保持不变，即$E[h'] = h$。\n",
    "\n",
    "## 实践中的dropout\n",
    "\n",
    "回想一下 :numref:`fig_mlp` 中带有一个隐藏层和5个隐藏单元的多层感知机。当我们将dropout应用到隐藏层，以$p$的概率将隐藏单元置为零时，结果可以看作是一个只包含原始神经元子集的网络。在 :numref:`fig_dropout2` 中，删除了$h_2$和$h_5$。因此，输出的计算不再依赖于$h_2$或$h_5$，并且它们各自的梯度在执行反向传播时也会消失。这样，输出层的计算不能过度依赖于$h_1, \\ldots, h_5$的任何一个元素。\n",
    "\n",
    "![dropout前后的多层感知机。](../img/dropout2.svg)\n",
    ":label:`fig_dropout2`\n",
    "\n",
    "通常，我们在测试时禁用dropout。给定一个训练好的模型和一个新的样本，我们不会丢弃任何节点，因此不需要标准化。然而，也有一些例外：一些研究人员使用测试时的dropout作为估计神经网络预测的“不确定性”的启发式方法：如果预测在许多不同的dropout掩码上都是一致的，那么我们可以说网络更有自信心。\n",
    "\n",
    "## 从零开始实现\n",
    "\n",
    "要实现单层的dropout函数，我们必须从伯努利（二元）随机变量中提取与我们的层的维度一样多的样本，其中随机变量以概率$1-p$取值$1$（保持），以概率$p$取值$0$（丢弃）。实现这一点的一种简单方式是首先从均匀分布$U[0, 1]$中抽取样本。那么我们可以保留那些对应样本大于$p$的节点，把剩下的丢弃。\n",
    "\n",
    "在下面的代码中，我们实现 `dropoutLayer()` 函数，该函数以`dropout`的概率丢弃`NDArray`输入`X`中的元素**)，如上所述重新缩放剩余部分：将剩余部分除以`1.0-dropout`。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils.ipynb\n",
    "%load ../utils/DataPoints.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/Accumulator.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以通过几个例子来测试`dropoutLayer()`函数。在下面的代码行中，我们将输入`X`通过`dropout`操作，丢弃概率分别为0、0.5和1。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "public NDArray dropoutLayer(NDArray X, float dropout) {\n",
    "    // In this case, all elements are dropped out\n",
    "    if (dropout == 1.0f) {\n",
    "        return manager.zeros(X.getShape());\n",
    "    }\n",
    "    // In this case, all elements are kept\n",
    "    if (dropout == 0f) {\n",
    "        return X;\n",
    "    }\n",
    "\n",
    "    NDArray mask = manager.randomUniform(0f, 1.0f, X.getShape()).gt(dropout);\n",
    "    return mask.toType(DataType.FLOAT32, false).mul(X).div(1.0f - dropout);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray X = manager.arange(16f).reshape(2, 8);\n",
    "System.out.println(dropoutLayer(X, 0));\n",
    "System.out.println(dropoutLayer(X, 0.5f));\n",
    "System.out.println(dropoutLayer(X, 1.0f));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义模型参数\n",
    "\n",
    "同样，我们使用 :numref:`sec_fashion_mnist` 中引入的Fashion-MNIST数据集。我们定义具有两个隐藏层的多层感知机，每个隐藏层包含256个单元。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int numInputs = 784;\n",
    "int numOutputs = 10;\n",
    "int numHiddens1 = 256;\n",
    "int numHiddens2 = 256;\n",
    "\n",
    "NDArray W1 = manager.randomNormal(0, 0.01f, new Shape(numInputs, numHiddens1), DataType.FLOAT32);\n",
    "NDArray b1 = manager.zeros(new Shape(numHiddens1));\n",
    "NDArray W2 = manager.randomNormal(0, 0.01f, new Shape(numHiddens1, numHiddens2), DataType.FLOAT32);\n",
    "NDArray b2 = manager.zeros(new Shape(numHiddens2));\n",
    "NDArray W3 = manager.randomNormal(0, 0.01f, new Shape(numHiddens2, numOutputs), DataType.FLOAT32);\n",
    "NDArray b3 = manager.zeros(new Shape(numOutputs));\n",
    "\n",
    "\n",
    "NDList params = new NDList(W1, b1, W2, b2, W3, b3);\n",
    "\n",
    "for (NDArray param : params) {\n",
    "    param.setRequiresGradient(true);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义模型\n",
    "\n",
    "下面的模型将dropout应用于每个隐藏层的输出（在激活函数之后）。我们可以分别为每一层设置丢弃概率。一种常见的技巧是在靠近输入层的地方设置较低的丢弃概率。\n",
    "下面，我们将第一个和第二个隐藏层的丢弃概率分别设置为0.2和0.5。\n",
    "通过使用:numref:`autograd`中描述的`isTraining`布尔变量，我们可以确保`dropout`仅在训练期间处于活动状态。我们确保`dropout`只在训练期间有效。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float dropout1 = 0.2f;\n",
    "float dropout2 = 0.5f;\n",
    "\n",
    "public NDArray net(NDArray X, boolean isTraining) {\n",
    "\n",
    "    X = X.reshape(-1, numInputs);\n",
    "    NDArray H1 = Activation.relu(X.dot(W1).add(b1));\n",
    "\n",
    "    if (isTraining) {\n",
    "        H1 = dropoutLayer(H1, dropout1);\n",
    "    }\n",
    "\n",
    "    NDArray H2 = Activation.relu(H1.dot(W2).add(b2));\n",
    "    if (isTraining) {\n",
    "        H2 = dropoutLayer(H2, dropout2);\n",
    "    }\n",
    "\n",
    "    return H2.dot(W3).add(b3);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 训练和测试\n",
    "\n",
    "这类似于前面描述的多层感知机训练和测试。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 10);\n",
    "float lr = 0.5f;\n",
    "int batchSize = 256;\n",
    "\n",
    "double[] trainLoss = new double[numEpochs];\n",
    "double[] trainAccuracy = new double[numEpochs];\n",
    "double[] testAccuracy = new double[numEpochs];\n",
    "double[] epochCount = new double[numEpochs];\n",
    "\n",
    "Loss loss = new SoftmaxCrossEntropyLoss();\n",
    "\n",
    "FashionMnist trainIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TRAIN)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "FashionMnist testIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TEST)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "                            \n",
    "trainIter.prepare();\n",
    "testIter.prepare();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float epochLoss = 0f;\n",
    "float accuracyVal = 0f;\n",
    "\n",
    "for (int epoch = 1; epoch <= numEpochs; epoch++) {\n",
    "    // Iterate over dataset\n",
    "    System.out.print(\"Running epoch \" + epoch + \"...... \");\n",
    "    for (Batch batch : trainIter.getData(manager)) {\n",
    "        NDArray X = batch.getData().head();\n",
    "        NDArray y = batch.getLabels().head();\n",
    "\n",
    "        try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "            NDArray yHat = net(X, true); // net function call\n",
    "\n",
    "            NDArray lossValue = loss.evaluate(new NDList(y), new NDList(yHat));\n",
    "            NDArray l = lossValue.mul(batchSize);\n",
    "\n",
    "            epochLoss += l.sum().getFloat();\n",
    "\n",
    "            accuracyVal += Training.accuracy(yHat, y);\n",
    "            gc.backward(l); // gradient calculation\n",
    "        }\n",
    "\n",
    "        batch.close();\n",
    "        Training.sgd(params, lr, batchSize); // updater\n",
    "    }\n",
    "\n",
    "    trainLoss[epoch-1] = epochLoss/trainIter.size();\n",
    "    trainAccuracy[epoch-1] = accuracyVal/trainIter.size();\n",
    "\n",
    "    epochLoss = 0f;\n",
    "    accuracyVal = 0f;\n",
    "\n",
    "    for (Batch batch : testIter.getData(manager)) {\n",
    "        NDArray X = batch.getData().head();\n",
    "        NDArray y = batch.getLabels().head();\n",
    "\n",
    "        NDArray yHat = net(X, false); // net function call\n",
    "        accuracyVal += Training.accuracy(yHat, y);\n",
    "    }\n",
    "\n",
    "    testAccuracy[epoch-1] = accuracyVal/testIter.size();\n",
    "    epochCount[epoch-1] = epoch;\n",
    "    accuracyVal = 0f;\n",
    "    System.out.println(\"Finished epoch \" + epoch);\n",
    "}\n",
    "\n",
    "System.out.println(\"Finished training!\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epochCount\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"loss\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epochCount\", \"loss\", \"lossLabel\"),\"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简洁实现\n",
    "\n",
    "用`DJL`，我们所需要做的就是在每个全连接层之后添加一个`Dropout`层，将丢弃概率作为唯一的参数传递给它的构造函数。在训练过程中，`Dropout`层将根据指定的丢弃概率随机丢弃上一层的输出（相当于下一层的输入）。当不处于训练模式时，`Dropout`层仅在测试时传递数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SequentialBlock net = new SequentialBlock();\n",
    "net.add(Blocks.batchFlattenBlock(784));\n",
    "net.add(Linear.builder().setUnits(256).build());\n",
    "net.add(Activation::relu);\n",
    "net.add(Dropout.builder().optRate(dropout1).build());\n",
    "net.add(Linear.builder().setUnits(256).build());\n",
    "net.add(Activation::relu);\n",
    "net.add(Dropout.builder().optRate(dropout2).build());\n",
    "net.add(Linear.builder().setUnits(10).build());\n",
    "net.setInitializer(new NormalInitializer(0.01f), Parameter.Type.WEIGHT);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们对模型进行训练和测试。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map<String, double[]> evaluatorMetrics = new HashMap<>();\n",
    "\n",
    "Tracker lrt = Tracker.fixed(0.5f);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "Loss loss = Loss.softmaxCrossEntropyLoss();\n",
    "\n",
    "DefaultTrainingConfig config = new DefaultTrainingConfig(loss)\n",
    "                .optOptimizer(sgd) // Optimizer (loss function)\n",
    "                .optDevices(manager.getEngine().getDevices(1)) // single GPU\n",
    "                .addEvaluator(new Accuracy()) // Model Accuracy\n",
    "                .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging\n",
    "\n",
    "    try (Model model = Model.newInstance(\"mlp\")) {\n",
    "        model.setBlock(net);\n",
    "\n",
    "        try (Trainer trainer = model.newTrainer(config)) {\n",
    "\n",
    "            trainer.initialize(new Shape(1, 784));\n",
    "            trainer.setMetrics(new Metrics());\n",
    "\n",
    "            EasyTrain.fit(trainer, numEpochs, trainIter, testIter);\n",
    "\n",
    "            Metrics metrics = trainer.getMetrics();\n",
    "\n",
    "            trainer.getEvaluators().stream()\n",
    "                    .forEach(evaluator -> {\n",
    "                        evaluatorMetrics.put(\"train_epoch_\" + evaluator.getName(), metrics.getMetric(\"train_epoch_\" + evaluator.getName()).stream()\n",
    "                                            .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "                        evaluatorMetrics.put(\"validate_epoch_\" + evaluator.getName(), metrics.getMetric(\"validate_epoch_\" + evaluator.getName()).stream()\n",
    "                                            .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "            });\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainLoss = evaluatorMetrics.get(\"train_epoch_SoftmaxCrossEntropyLoss\");\n",
    "trainAccuracy = evaluatorMetrics.get(\"train_epoch_Accuracy\");\n",
    "testAccuracy = evaluatorMetrics.get(\"validate_epoch_Accuracy\");\n",
    "\n",
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"test acc\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"train loss\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epochCount\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"loss\", ArrayUtils.addAll(testAccuracy , ArrayUtils.addAll(trainAccuracy, trainLoss))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epochCount\", \"loss\", \"lossLabel\"),\"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 除了控制权重向量的维数和大小之外，dropout也是避免过拟合的另一种工具。它们通常是联合使用的。\n",
    "* dropout将激活值$h$替换为具有期望值$h$的随机变量。\n",
    "* dropout仅在训练期间使用。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 如果更改第一层和第二层的dropout概率，会发生什么情况？具体地说，如果交换这两个层，会发生什么情况？设计一个实验来回答这些问题，定量描述你的结果，并总结定性的结论。\n",
    "1. 增加迭代周期数，并将使用dropout和不使用dropout时获得的结果进行比较。\n",
    "1. 当应用或不应用dropout时，每个隐藏层中激活值的方差是多少？绘制一个曲线图，以显示这两个模型的每个隐藏层中激活值的方差是如何随时间变化的。\n",
    "1. 为什么在测试时通常不使用dropout？\n",
    "1. 以本节中的模型为例，比较使用dropout和权重衰减的效果。如果同时使用dropout和权重衰减，会发生什么情况？结果是累加的吗？收益是否减少（或者说更糟）？它们互相抵消了吗？\n",
    "1. 如果我们将dropout应用到权重矩阵的各个权重，而不是激活值，会发生什么？\n",
    "1. 发明另一种用于在每一层注入随机噪声的技术，该技术不同于标准的dropout技术。你能否开发一种在Fashion-MNIST数据集(对于固定结构)上性能优于dropout的方法？\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
